package com.bhkj.pdjhforotherapp.core.sure;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.bhkj.pdjhforotherapp.R;
import com.bhkj.pdjhforotherapp.common.Contact;
import com.bhkj.pdjhforotherapp.common.bean.JhResultBean;
import com.bhkj.pdjhforotherapp.common.bean.MainYwAllBean;
import com.bhkj.pdjhforotherapp.common.bean.QueueBusiness;
import com.bhkj.pdjhforotherapp.common.bean.SelectedItemBean;
import com.bhkj.pdjhforotherapp.common.callback.CallbackManager;
import com.bhkj.pdjhforotherapp.common.callback.IGlabolCallback;
import com.bhkj.pdjhforotherapp.common.parse.GsonProvider;
import com.bhkj.pdjhforotherapp.common.simpledisk.DiskLruCacheHelper;
import com.bhkj.pdjhforotherapp.common.utils.NetIpUtils;
import com.bhkj.pdjhforotherapp.common.utils.Tools;
import com.bhkj.pdjhforotherapp.common.utils.UpdateUtil;
import com.bhkj.pdjhforotherapp.common.view.ShadowDrawable;
import com.bhkj.pdjhforotherapp.core.base.BaseActivity;
import com.bhkj.pdjhforotherapp.core.main.view.MainYwActivity;
import com.bhkj.pdjhforotherapp.core.printutilspjq.PrintManagerPjq;
import com.bhkj.pdjhforotherapp.core.readsfzprint.JHDetailActivity;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.CacheDiskStaticUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import net.lemonsoft.lemonhello.LemonHello;
import net.lemonsoft.lemonhello.LemonHelloAction;
import net.lemonsoft.lemonhello.LemonHelloInfo;
import net.lemonsoft.lemonhello.LemonHelloView;
import net.lemonsoft.lemonhello.interfaces.LemonHelloActionDelegate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

@SuppressWarnings("unchecked")
public class SelectedYwSureActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView mRv;
    private SelectedYwAdapter mSelectedYwAdapter;
    private TextView mTvTime;

    @Override
    public int getLayoutId() {
        return R.layout.activity_selected_yw_sure;
    }

    @Override
    public void initView() {
        mRv = findViewById(R.id.rv_selected_yw_list);
        TextView pickNum = findViewById(R.id.bt_selected_yw_picknum);
        pickNum.setOnClickListener(this);
        TextView back = findViewById(R.id.tv_selected_yw_back);
//        findViewById(R.id.tv_selected_yw_next_page).setOnClickListener(this);
        back.setOnClickListener(this);
        findViewById(R.id.iv_selected_yw_logo).setOnClickListener(this);
        //顶部渐变颜色
        View viewTop = findViewById(R.id.divider_top_selected);
        ShadowDrawable.setShadowDrawable(viewTop, new int[]{
                        Color.parseColor("#536DFE"), Color.parseColor("#7C4DFF")}, SizeUtils.dp2px(1),
                Color.parseColor("#997C4DFF"), SizeUtils.dp2px(1), SizeUtils.dp2px(1), SizeUtils.dp2px(1));
        mTvTime = findViewById(R.id.tv_selected_yw_time);
        TextView vipTvPickup = findViewById(R.id.bt_selected_yw_vip_pick);
        vipTvPickup.setOnClickListener(this);
        TextView clearAllTv = findViewById(R.id.tv_selected_yw_clear_all);
        clearAllTv.setOnClickListener(this);
        //按钮渐变色
        setShadowForView(pickNum, back, vipTvPickup, clearAllTv);
    }

    /**
     * 给view添加阴影效果
     *
     * @param pickNum
     * @param back
     * @param vipTvPickup
     * @param clearAllTv
     */
    private void setShadowForView(TextView pickNum, TextView back, TextView vipTvPickup, TextView clearAllTv) {
        ShadowDrawable.setShadowDrawable(pickNum, new int[]{
                        Color.parseColor("#CE9FFC"), Color.parseColor("#7367F0")},
                SizeUtils.dp2px(6),
                Color.parseColor("#99CE9FFC"),
                SizeUtils.dp2px(6), SizeUtils.dp2px(5), SizeUtils.dp2px(2));

        ShadowDrawable.setShadowDrawable(back, new int[]{
                        Color.parseColor("#6495ed"), Color.parseColor("#556b2f")},
                SizeUtils.dp2px(6),
                Color.parseColor("#996495ed"),
                SizeUtils.dp2px(6), SizeUtils.dp2px(5), SizeUtils.dp2px(2));

        ShadowDrawable.setShadowDrawable(clearAllTv, new int[]{
                        Color.parseColor("#FCCF31"), Color.parseColor("#F55555")},
                SizeUtils.dp2px(6),
                Color.parseColor("#99FCCF31"),
                SizeUtils.dp2px(6), SizeUtils.dp2px(5), SizeUtils.dp2px(2));

        ShadowDrawable.setShadowDrawable(vipTvPickup, new int[]{
                        Color.parseColor("#008000"), Color.parseColor("#006400")},
                SizeUtils.dp2px(6),
                Color.parseColor("#99008000"),
                SizeUtils.dp2px(6), SizeUtils.dp2px(5), SizeUtils.dp2px(2));
    }

    @Override
    public void initData() {
        initTime();
        initRecyclerView();
        showSelectedYw();
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
        mRv.setLayoutManager(layoutManager);
        mSelectedYwAdapter = new SelectedYwAdapter(R.layout.item_yw, null);
        mRv.setAdapter(mSelectedYwAdapter);
        mSelectedYwAdapter.bindToRecyclerView(mRv);
    }

    /**
     * 初始化日期展示 年月日 周 时分秒
     * yyyy-MM-dd HH:mm:ss
     */
    private void initTime() {
        //每秒更新一次时间
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Date date = new Date();
                        String year = TimeUtils.date2String(date, "yyyy");
                        String month = TimeUtils.date2String(date, "MM");
                        String day = TimeUtils.date2String(date, "dd");
                        String week = TimeUtils.getChineseWeek(date);
                        String time = TimeUtils.date2String(date, "HH:mm:ss");
                        final String finalTime = year + "年" + month + "月" + day + "日 " + week + " " + time;
                        mTvTime.setText(finalTime);
                    }
                });
            }
        };

        timer.schedule(timerTask, 0, 1000);
    }

    @SuppressWarnings("unchecked")
    private void showSelectedYw() {
        List<SelectedItemBean> allSelectedItemBeans = new ArrayList<>();
        //添加已选择的业务
        String res = SPUtils.getInstance().getString(CacheDiskStaticUtils.getString(Contact.SAVE_YW_SELECTED));
//        LogUtils.i(DiskLruCacheHelper.getInstance().getAsString(Contact.SAVE_YW_SELECTED) + "\n" + res);
        HashMap<String, SelectedItemBean> selectedItemBeans = GsonProvider.getInstance().getGson().fromJson(res, new TypeToken<HashMap<String, SelectedItemBean>>() {}.getType());
        if (ObjectUtils.isNotEmpty(selectedItemBeans)) {
            String businessStr = CacheDiskStaticUtils.getString(Contact.YW_ALL_LIST);
            List<MainYwAllBean.Datas.Business> businessArray = GsonUtils.fromJson(businessStr, new TypeToken<List<MainYwAllBean.Datas.Business>>() {
            }.getType());
            final int size = businessArray.size();
            for (String key : selectedItemBeans.keySet()) {
                for (int i = 0; i < size; i++) {
                    if (businessArray.get(i).getId().equals(Objects.requireNonNull(selectedItemBeans.get(key)).getYwlxId())) {
                        SelectedItemBean selectedItemBean = selectedItemBeans.get(key);
                        selectedItemBean.setYwlxName(businessArray.get(i).getContent());
                        selectedItemBean.setOwnerName(businessArray.get(i).getOwnername());
                        selectedItemBean.setYwMaxNum(businessArray.get(i).getMax());
                        allSelectedItemBeans.add(selectedItemBean);
                    }

                }
            }
        }

//        Log.i("mine", allSelectedItemBeans.toString());

        mSelectedYwAdapter.setNewData(allSelectedItemBeans);
    }


    @SuppressLint("NewApi")
    @Override
    public void onClick(View v) {
        final int viewId = v.getId();
        switch (viewId) {
            case R.id.bt_selected_yw_picknum:
                toJhDetail(Contact.COMMON_WINDOW);
                break;
            case R.id.tv_selected_yw_back:
                finish();
                overridePendingTransition(R.anim.right_to_left, R.anim.left_to_right);
                break;
            //清除所有选中的业务
            case R.id.tv_selected_yw_clear_all:
                clearAllYwTip();
                break;
            //检查版本更新
            case R.id.iv_selected_yw_logo:
                UpdateUtil.checkUpdate(this, true);
                break;
            case R.id.bt_selected_yw_vip_pick:
                toJhDetail(Contact.VIP_WINDOW);
                break;
            default:
                break;
        }
    }

    /**
     * 将选中的业务转换成json字符串传递到叫号详情页，刷完身份证将数据传递到服务中进行保存
     */
    private void toJhDetail(String qhType) {

        List<SelectedItemBean> data = mSelectedYwAdapter.getData();
        List<QueueBusiness> queueBusinesses = new ArrayList<>();
        for (SelectedItemBean param : data) {
            QueueBusiness queueBusiness = new QueueBusiness();
            queueBusiness.setBid(param.getId());
            queueBusiness.setBunum(param.getCount());
            queueBusinesses.add(queueBusiness);
        }
        String queueBusinessJson = GsonProvider.getInstance().getGson().toJson(queueBusinesses);
        if (getResources().getBoolean(R.bool.isQhj)) {
            Intent intent = new Intent(this, JHDetailActivity.class);
            intent.putExtra(Contact.SURE_YW, queueBusinessJson);
            intent.putExtra(Contact.QHTYPE, qhType);
            startActivity(intent);
        } else {
            saveSelectedYwToServer(queueBusinessJson, qhType, "0", "123456789012345678");
        }
    }

    /**
     * 保存叫号的数据到服务器上
     *
     * @param name  姓名
     * @param idNum 身份证号
     */
    private void saveSelectedYwToServer(String queueBusiness, String qhType, String name, String idNum) {
        if (!NetworkUtils.isConnected()) {
            ToastUtils.showShort(R.string.tip_connect_net_content);
            return;
        }
        showLoading();

        try {
            name = URLEncoder.encode(name, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        net(queueBusiness, qhType, name, idNum);
    }

    /**
     * 网络实际执者
     *
     * @param queueBusiness 选择业务数据
     * @param name          姓名
     * @param idNum         身份证号
     */
    private void net(String queueBusiness, String qhType, String name, String idNum) {
        String deviceId = Tools.getDeviceId();
//        LogUtils.e("ip地址", NetIpUtils.getLocalIPAddress());
        EasyHttp.post(Contact.SAVE_YW_TO_SERVEr)
                .params("key", deviceId)
                .params("rsa", Tools.encodeRsa(deviceId))
                .params("xm", name)
                .params("sfzhm", idNum)
                .params("deptid", getResources().getString(R.string.deptId))
                .params("windowtype", qhType)
                .params("queueBusiness", queueBusiness)
                .params("ip", NetIpUtils.getLocalIPAddress().getHostAddress())
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        LogUtils.i(e.getMessage() + e.getCode());
                        dismissLoading();
                        onErrorTip(getString(R.string.error_again) + e.getMessage());
                    }

                    @Override
                    public void onSuccess(String s) {
                        LogUtils.i(s);
                        dismissLoading();
                        handleJhSuccessResult(s);
                    }
                });

    }

    /**
     * 处理实际的业务
     *
     * @param s 服务器返回的数据
     */
    private void handleJhSuccessResult(String s) {
        if (TextUtils.isEmpty(s)) {
            onErrorTip("空数据");
            return;
        }
        LogUtils.i(s);
        final JhResultBean jhResultBean = GsonProvider.getInstance().getGson().fromJson(s, JhResultBean.class);
        if (jhResultBean != null) {
            //打印小票
            if (jhResultBean.isSuccess()) {
                PrintManagerPjq.getInstance().print(jhResultBean,null);
                //清除缓存数据
                //保存选中的业务信息
                finish();
                ActivityUtils.startActivity(MainYwActivity.class);
                clear();
            } else {
                onErrorTip(jhResultBean.getMessage());
            }
        } else {
            onErrorTip("叫号数据返回为空");
        }
    }

    private void clear() {
        IGlabolCallback callback = CallbackManager.getInstance().getCallback(Contact.CLEAER_SELECTED_DATA);
        if (callback != null) {
            callback.executeCallback("");
        }
        SPUtils.getInstance().clear();
        CacheDiskStaticUtils.remove(Contact.SAVE_YW_SELECTED);

    }


    /**
     * 访问保存数据接口出错后的提示对话框，可以接着访问
     * 或者是关闭页面停止访问接口
     *
     * @param tip 提示信息
     */
    private void onErrorTip(String tip) {

        if (ActivityUtils.isActivityAlive(this)) {
            LemonHello.getErrorHello(tip, tip)
                    .addAction(new LemonHelloAction(getString(R.string.close), new LemonHelloActionDelegate() {
                        @Override
                        public void onClick(LemonHelloView lemonHelloView, LemonHelloInfo lemonHelloInfo, LemonHelloAction lemonHelloAction) {
                            lemonHelloView.hide();
                        }
                    })).show(this);
        }
    }

    /**
     * 清除所有选择的业务
     */
    private void clearAllYwTip() {
        LemonHello.getInformationHello("清除所选中的业务", "")
                .addAction(new LemonHelloAction(getString(R.string.cancel), new LemonHelloActionDelegate() {
                    @Override
                    public void onClick(LemonHelloView lemonHelloView, LemonHelloInfo lemonHelloInfo, LemonHelloAction lemonHelloAction) {
                        //隐藏提示
                        lemonHelloView.hide();
                    }
                }))
                .addAction(new LemonHelloAction(getString(R.string.sure), new LemonHelloActionDelegate() {
                    @Override
                    public void onClick(LemonHelloView lemonHelloView, LemonHelloInfo lemonHelloInfo, LemonHelloAction lemonHelloAction) {
                        lemonHelloView.hide();
                        //清除所有选中的业务
                        clear();
                        finish();
                    }
                })).show(this);
    }

}
